// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// I [author] rhyme_lph
// D [email]  rhymelph@gmail.com
// g [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/entities/invite_member_entity.dart';
import 'package:finance_app/src/entities/role_permission_entity.dart';
import 'package:finance_app/src/http_service/http_employee_contact_service.dart';
import 'package:finance_app/src/http_service/http_invitation_service.dart';
import 'package:finance_app/src/http_service/http_permission_service.dart';
import 'package:finance_app/src/mixin/search_data_map_mixin.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/list_select_bottom_sheet.dart';
import 'package:flutter/material.dart';

class AssignRoleByBatchProvider extends BaseProvider<List<InviteMemberEntity>>
    with SearchDataMapMixin<List<InviteMemberEntity>, InviteMemberEntity> {
  List<InviteMemberEntity> currentSelectList = [];
  List<RolePermissionEntity> roles = [];

  bool isSelectMode = false;
  bool isPayslip = false;

  @override
  Future get dataFuture => HttpInvitationService.invitationMembers('active');

  @override
  void initState() {
    super.initState();
    loadRoles();
  }

  void onNext() async {
    if (currentSelectList.length == 0) return;
    obtainContext?.call((context) async {
      final role = await showRolesBottomSheet(context, roles,
          title: S.current.assign_role_by_batch);
      if (role != null) {
        bool isSuccess = false;

        await post(
            HttpPermissionService.setUserRoles(
              role.id,
              role.name,
              users: currentSelectList.map((e) => {'id': e.id}).toList(),
            ),
            autoHandler: AutoHandler.Toast,
            loadingTip: S.current.loading, onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess) {
          Navigator.pop(context, true);
        }
      }
    });
  }

  void onSelectDetail(InviteMemberEntity value) {
    if (currentSelectList.contains(value)) {
      currentSelectList.remove(value);
    } else {
      currentSelectList.add(value);
    }
    update();
  }

  @override
  FutureOr<List<InviteMemberEntity>> transformData(
      List<InviteMemberEntity> d, bool isCache) {
    d.sort((a, b) => a.name.compareTo(b.name));
    for (final item in d) {
      searchDataClassification(item);
    }
    return d;
  }

  void searchDataClassification(InviteMemberEntity item) {
    if (item.name.length > 0) {
      String firstName = item.name[0].toUpperCase();
      if (searchData.containsKey(firstName.toUpperCase())) {
        searchData[firstName].add(item);
      } else {
        searchData[firstName] = [item];
      }
    } else {
      if (searchData['*'] != null) {
        searchData["*"].add(item);
      } else {
        searchData['*'] = [item];
      }
    }
  }

  void loadRoles() async {
    await post(HttpPermissionService.getAllRoles(), onSuccess: (result) {
      roles = getEntityFromResult<List<RolePermissionEntity>>(result);
    });
    update();
  }

  void onDeselectAll() {
    currentSelectList.clear();
    update();
  }

  void onSelectAll() {
    currentSelectList.clear();
    currentSelectList.addAll(data);
    update();
  }
}
